package com.shqcjd.preinstallglass.ui.activity.remote;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.orhanobut.logger.Logger;
import com.shqcjd.preinstallglass.R;
import com.shqcjd.preinstallglass.app.MyApp;
import com.shqcjd.preinstallglass.ui.base.BaseActivity;
import com.shqcjd.preinstallglass.ui.base.BasePresenter;
import com.shqcjd.preinstallglass.util.DateUtil;
import com.shqcjd.preinstallglass.util.PrefUtils;
import com.shqcjd.preinstallglass.util.ToastUtils;
import com.shqcjd.preinstallglass.widget.BlurTransformation;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import io.agora.AgoraAPI;
import io.agora.AgoraAPIOnlySignal;
import io.agora.IAgoraAPI;
import rippleview.huang.com.RippleView;

/**
 * 视频呼叫
 */
public class VideoCallActivity extends BaseActivity {


    @BindView(R.id.iv_bg_img)
    ImageView ivBgImg;
    @BindView(R.id.civ_icon)
    CircleImageView civIcon;
    @BindView(R.id.fl_close_btn)
    FrameLayout flCloseBtn;
    @BindView(R.id.ripple_player)
    RippleView ripple_player;
    private String expertId;
    private AgoraAPIOnlySignal mAgoraAPI;
    private Context mContext;
    private String channeName;
    private int equipmentId;
    private int taskId;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_video_call;
    }

    @Override
    public void initView() {
        mContext = this;
        expertId = getIntent().getStringExtra("expertId");
        equipmentId = getIntent().getIntExtra("equipmentId", -1);
        taskId = getIntent().getIntExtra("taskId", -1);

        initBlur();
        initRipple();

        initLogin();

    }

    /**
     * 登录信令
     */
    private void initLogin() {
        mAgoraAPI = MyApp.the().getmAgoraAPI();
        int userId = PrefUtils.getInt(this, PrefUtils.USER_ID, -1);
        //登出
        mAgoraAPI.logout();
        //登录声网信令系统
        mAgoraAPI.login2(getString(R.string.agora_app_id), userId + "", "_no_need_token", 0, "", 5, 3);
    }

    /**
     * 巡查专家在线状态
     */
    private void queryUserStatus() {
        long curTimeLong = DateUtil.getCurTimeLong();
        channeName = "yuhuan@"+curTimeLong;
        //查询对方是否在线
        mAgoraAPI.queryUserStatus(expertId);
    }

    @Override
    protected void onResume() {
        super.onResume();
        addCallback();

    }

    private void addCallback() {
        if (mAgoraAPI == null) {
            return;
        }

        mAgoraAPI.callbackSet(new AgoraAPI.CallBack() {

            //Agora 信令登录成功
            @Override
            public void onLoginSuccess(int i, int i1) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Logger.i("Agora 信令登录成功:" + i + "  " + i1);
                        queryUserStatus();
                    }
                });
            }

            @Override
            public void onLogout(int i) {
                Logger.i("Agora 信令登出");
            }

            @Override
            public void onLoginFailed(final int i) {
                Logger.e("Agora 信令onLoginFailed");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (i == IAgoraAPI.ECODE_LOGIN_E_NET) {
                            ToastUtils.showShort(mContext,"网络连接失败");
                            finish();
                        }
                    }
                });
            }


            //当呼叫被对方收到时触发。，本地将回调 onInviteReceivedByPeer, 对方会回调 onInviteReceived。
            @Override
            public void onInviteReceivedByPeer(final String channelID, final String account, int uid) {//call out other local receiver


            }

            //当呼叫被对方接受时触发此回调。
            @Override
            public void onInviteAcceptedByPeer(String channelID, final String account, int uid, String extra) {
                super.onInviteAcceptedByPeer(channelID, account, uid, extra);
                Logger.i("对方接受:"+channelID+ " "+account);
                Intent intent = new Intent(mContext, PushVideoActivity.class);
                intent.putExtra("channelID", channelID);
                intent.putExtra("expertID", account);
                intent.putExtra("equipmentId", equipmentId);
                intent.putExtra("taskId", taskId);
                startActivity(intent);
                finish();

            }

            //当呼叫被对方拒绝时触发此回调
            @Override
            public void onInviteRefusedByPeer(String channelID, String account, int uid, String extra) {
                super.onInviteRefusedByPeer(channelID, account, uid, extra);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtils.showShort(mContext,"对方拒绝通话");
                        finish();
                    }
                });

            }

            @Override
            public void onInviteFailed(String channelID, String account, int uid, int i1, String s2) {
                Logger.i("onInviteFailed  channelID = " + channelID + " account = " + account + " s2: " + s2 + " i1: " + i1);
            }

            @Override
            public void onError(final String s, int i, final String s1) {
                Logger.i("onError s = " + s + " i = " + i + " s1 = " + s1);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (s.equals("query_user_status")) {
                            Logger.i(s1);
                        }
                    }
                });
            }

            //用户状态查询回调 (onQueryUserStatusResult) 1: 用户在线 0: 用户离线
            @Override
            public void onQueryUserStatusResult(final String name, final String status) {
                Logger.i("onQueryUserStatusResult name:"+name+" status:"+status);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (status.equals("1")) {
                            //加入指导频道
                            mAgoraAPI.channelJoin(channeName);
                        } else if (status.equals("0")) {
                            ToastUtils.showShort(mContext,"对方离线状态");
                            finish();
                        }
                    }
                });
            }

            //结束呼叫 本端会回调 onInviteEndByMyself，对端会回调 onInviteEndByPeer
            @Override
            public void onInviteEndByMyself(String channelID, String account, int uid) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                    }
                });
            }

            /**
             * 加入信令频道成功
             * @param channelID
             */
            @Override
            public void onChannelJoined(String channelID) {
                super.onChannelJoined(channelID);
                Logger.e("加入成功: 房间号:" + channelID);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //发起呼叫   成功：自己收到 ICallBack 类的 onInviteAcceptedByPeer() 回调
                        mAgoraAPI.channelInviteUser2(channelID, expertId, null);

                    }
                });
            }
        });
    }


    /**
     * 设置水波纹
     */
    private void initRipple() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                ripple_player.toggle();
            }
        },1000);
    }

    /**
     * 设置背景模糊
     */
    private void initBlur() {
        // 高斯模糊
        Drawable drawable = ActivityCompat.getDrawable(this, R.mipmap.touxiang1);
        Glide.with(this)
                .load(drawable)
                .apply(RequestOptions.bitmapTransform(new BlurTransformation(this,20, 6)))
                .into(ivBgImg);
    }




    @OnClick(R.id.fl_close_btn)
    public void onViewClicked() {
        //取消呼叫
        mAgoraAPI.channelInviteEnd(channeName, expertId, 0);
        finish();
    }

    @Override
    protected String getVoiceContent() {
        return "|取消;";
    }

    @Override
    protected void onVoiceResult(String result) {
        Logger.i("识别结果:"+result);
        switch (result) {
            case "取消":
                flCloseBtn.performClick();
                break;
        }
    }
}
